<template>
  <PageView
      ref="pageViewRef"
      :scrollable="false"
      :layout-vars="{showFooter:total>0}"
      v-loading="loading"
      :element-loading-text="loadingText"
  >
    <template #header>
      <div class="app-section-header">
        <el-form
            :model="queryParams"
            ref="queryForm"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
        >
          <el-form-item label="支付日期">
            <el-date-picker
                v-model="dateRange"
                type="daterange"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :shortcuts="shortcuts">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            <el-button type="danger" icon="Upload" @click="uploadQuery">推送当前页数据</el-button>
          </el-form-item>
        </el-form>
      </div>
    </template>

    <template v-slot:default="{contentHeight}">
      <el-table
          ref="table"
          :data="tableData"
          :height="contentHeight == 0 ? 200 : contentHeight"
          border
          scrollbar-always-on
          @selection-change="handleSelectionChange"
      >
        <el-table-column label="序号" type="index" width="55" align="center" />
        <el-table-column prop="transportBillNumber" label="运单号"  align="center"></el-table-column>
        <el-table-column prop="payTypeText" label="支付方式"  align="center"></el-table-column>
        <el-table-column prop="payCostText" label="支付金额（元）"  align="center"></el-table-column>
        <el-table-column prop="payTransactionNo" label="支付流水号"  align="center"></el-table-column>
        <el-table-column prop="payTimeText" label="支付时间"  align="center"></el-table-column>
        <el-table-column prop="receiptNo" label="电子回单号"  align="center">
          <template v-slot="scope">
            <div class="link-type" @click="scanReceipePdf(scope.row)">{{scope.row.receiptNo}}</div>
          </template>
        </el-table-column>

      </el-table>
    </template>

    <template #footer>
      <div class="app-section-footer">
        <Pagination
            v-show="total>0"
            :total="total"
            :pageSize="queryParams.pageSize"
            :currentPage="queryParams.pageNum"
            @pagination="getList"
        />
      </div>
    </template>

  </PageView>
</template>

<script lang="ts" setup>

</script>

<style>

</style>

<script>
/* eslint-disable */
import {getPayDetailInfoInfo} from "@/api/khy-operatingcenter";
import { uploadKhyWaybill } from '@/api/ky-api/ky-api'
import {getNowTimeStrWithFormatter, getTimestampByStr, getTimeWithFormatter} from '@/utils/util'

// 快货运 - 支付明细表
export default {
  name: "PayDetail",
  components:{
  },
  props:{

  },
  data() {
    return {
      tableData:[],
      multipleSelection:[],

      // 加载状态
      loading:false,
      loadingText:null,

      // 分页相关参数
      total:0,

      // 是否显示搜索
      showSearch:true,

      // 查询参数相关
      queryParams:{
        pageNum:1,
        pageSize:this.$store.state.pageSizeMax,
        businessScopeType:null,
        companyName:null,
        // 回单付
        payType:20400,
        payWay:null,
        payeeName:null,
        payeePhone:null,
        projectName:null,
        taxSourceId:null,
        timeEnd:getTimeWithFormatter(),
        timeStart:1696089600000,
        // 最大时间区间设置（1个月为30d）
        timeType:60,
        transportBillNumber:null,
      },

      // 日期范围
      dateRange: [],
      // 开始结束时间级联事件选择配置数据 - 最近时间
      shortcuts:[
        {
          text: '最近一周',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
          },
        },
        {
          text: '最近一个月',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
          },
        },
        {
          text: '最近三个月',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            return [start, end]
          },
        },
      ],

      // 控制弹窗显示
      dialogVisible:false,
      dialogTitle:"查看",
      urls:[],
    }
  },
  beforeCreate() {

  },
  setup() {

  },
  created() {
    // 两个月内的 截止时间为上上一天零点
    let nowTime = new Date() - 2 * 24 * 3600 * 1000;
    let endTime = getTimeWithFormatter(nowTime, 'yyyy-MM-dd')

    // 开始时间往前推两个月
    let startTime = nowTime - 60 * 24 * 3600 * 1000;
    let startTimeStr = getTimeWithFormatter(startTime, 'yyyy-MM-dd')
    this.dateRange = [startTimeStr, endTime];

    this.getList()
  },
  mounted() {
    console.log('路由传入的参数信息', this.$route.query)
  },
  activated() {
    console.log('keep-alive被激活时调用')
  },
  methods:{
    getList(pageInfo) {
      this.loading = true
      this.updatePageInfo(pageInfo)

      let param = this.getParams()
      getPayDetailInfoInfo(param).then(res => {
        const result = res.data ? res.data : {}
        this.loading = false
        this.total = result.total
        this.tableData = result.records
      }).catch(err => {
        console.log('获取支付明细数据失败：', err)
        this.loading = false
      })
    },

    /**
     * 获取请求参数
     * @returns {{transportBillNumber: null, closeStatus: number, informationPaymentBankCardNumber: null, shipperInvoiceStatus: null, carLicensePlate: null, creatorName: null, pageSize: number, timeType: string, businessScopeType: null, transportBillStatus: null, routeName: null, driverInvoiceStatus: null, startTime: number, taxSourceId: null, insuranceCompany: null, informationPaymentBankAccountName: null, riskStatusList: [], pageNum: number, companyId: null, discardStatus: number, shipperTransportBillNumber: null, driverName: null, driverPhone: null, endTime: number, projectName: null}}
     */
    getParams() {
      let startTime = null;
      let endTime = null;
      if (this.dateRange && this.dateRange.length > 0) {
        let str = this.dateRange[0] + ' 00:00:00'
        startTime = getTimestampByStr(str);
        console.log('startTime:', startTime)
      }
      if (this.dateRange && this.dateRange.length > 1) {
        let str = this.dateRange[1] + ' 23:59:59:999'
        endTime = getTimestampByStr(str);
        console.log('endTime:', endTime);
      }
      this.queryParams.timeStart = startTime;
      this.queryParams.timeEnd = endTime;
      return this.queryParams
    },

    /**
     * 获取展示的时间
     * @param time
     * @returns {string}
     */
    getShowTime(time, formatter) {
      return getTimeWithFormatter(time, formatter)
    },

    /**
     * 分页组件变动 更新分页标记数据
     * @param val
     */
    updatePageInfo(val) {
      if (val) {
        this.queryParams.pageSize = val.pageSize
        this.queryParams.pageNum = val.pageNum
      }
    },

    /**
     * 单元格多选方法
     * @param val
     */
    handleSelectionChange(selection) {
      this.multipleSelection = selection;
      console.log('当前选择的单元格数据', this.multipleSelection)
    },

    /**
     * 搜索按钮点击事件
     */
    handleQuery() {
      console.log('handleQuery:', this.queryParams)
      console.log('dateRange:', this.dateRange)
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /**
     * 查询表单重置
     */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.handleQuery()
    },

    /**
     * 将查询到的数据同步保存至开运系统
     */
    uploadQuery() {
      if (this.tableData.length == 0) {
        return
      }
      let platform = this.$store.state.customerName;
      let custom = this.$store.state.user.name;
      let queryParam = this.getParams();
      let data = this.tableData;
      let info = {}
      info.platform = platform
      info.custom = custom
      info.queryParam = queryParam
      info.data = data
      info.dataType = 3;
      this.loading = true;
      this.loadingText = "导入中..."
      uploadKhyWaybill(info).then(res => {
        console.log('导入支付明细数据到开运成功')
        this.loading = false
        this.$message.success('本页数据导入成功')
      }).catch(err => {
        console.log('导入支付明细数据到开运失败')
        this.loading = false
      })
    },

    /**
     * 姓名点击事件
     */
    nameClicked() {
      // 开一个新的二级页面
      this.$router.push('/main/userInfo')
    },

    /**
     * 弹窗关闭
     */
    handleClose() {
      this.dialogVisible = false
    },

    editBtnClicked() {
      console.log('编辑')
    },

    deleteBtnClicked() {
      console.log('删除')
      this.$modal.showConfirmAlert('提示', '确认删除吗?')
          .then(() => {

            this.$message.success('删除成功')
          })
          .catch(() => {
            this.$message.info('取消')
          })
    },

    /**
     * 查看支付回单号附件
     * @param row
     */
    scanReceipePdf(row) {
      let url = row.receiptDownloadUrl ? row.receiptDownloadUrl : '';
      if (url.length > 0) {
        window.open(url);
      }
    },


    /**
     * 查看司机详情信息图片
     * @param scope 查看行
     * @param type 查看类型 0身份证图片
     */
    scanDriverInfo(scope, type) {
      if (scope) {
        let row = scope.row
        let title = scope.column.label
        let str = ''
        let arr = []
        if (type == 0) {
          // 身份证
          arr.push(row.idCardFrontFilename);
          arr.push(row.idCardBackFilename);
        }
        const param = {
          filenames:arr
        }

        let imageUrls = []
        // getDriverImageInfo(param).then(res => {
        //   console.log('获取图片信息：', res)
        //   let data = res.data ? res.data : {}
        //   for (const imageKey of arr) {
        //     const imageInfo = data[imageKey]
        //     const imageUrl = imageInfo.url
        //     imageUrls.push(imageUrl)
        //   }
        //   console.log('imageUrls:', imageUrls)
        //   this.urls = imageUrls
        //   this.dialogTitle = title
        //   this.dialogVisible = true
        // }).catch(err => {
        //   console.log('获取图片信息失败：', err)
        // })
      }
    },
  }
}
</script>

<style lang="scss" scoped>

</style>
